import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Message, Checkbox } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import MemberTrigger from 'components/memberTrigger';
import exceed from 'utils/apimap';
import './index.scss';
import intl from '../../../../../../../../../../../locale';

const { id: orgId } = window.FORCE.organization;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 4,
  },

  wrapperCol: {
    span: 20,
  },
};

const operationTypes = [
  {
    value: 'REPO_OPERATION',
    label: intl.get({
      id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.DatabaseOperations',
      defaultMessage: '库操作',
    }),
  },

  {
    value: 'AUTHORITY_CHANGE',
    label: intl.get({
      id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.PermissionChange',
      defaultMessage: '权限变更',
    }),
  },
];

export default class TagModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    onCancel: PropTypes.func,
    onClose: PropTypes.func,
    formSubmit: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      isModalOpen: false,
      submitting: false,
      data: {},
    };
  }

  static getDerivedStateFromProps(props, state) {
    const newData = {
      ...(props.data || {}),
      ...state.data,
    };

    if (props.trigger) {
      return {
        data: newData,
      };
    }
    return {
      isModalOpen: props.isModalOpen,
      data: newData,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.onClose();
  };

  onHandleSubmit = () => {
    const { submitting, data } = this.state;
    if (submitting) {
      return;
    }

    if (!(data.users && data.users.length)) {
      this.setUserError(true);
    }
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        this.setState({ submitting: true });
        this.createRule(formData);
      } else {
        this.setState({ submitting: false });
      }
    });
  };

  typeValidator = (rule, value, callback) => {
    // 没选或者选了取消时
    if (!(value && value.length) || (value.length === 1 && value[0] === '')) {
      callback(
        intl.get({
          id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.ThisParameterIsRequired',
          defaultMessage: '该项为必填项',
        }),
      );
      return;
    }
    callback();
  };

  ipValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    const ipList = value.split(',');
    if (ipList.length > 1000) {
      callback(
        intl.get({
          id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.TheSpecifiedNumberExceeds',
          defaultMessage: '超过限定数量1000',
        }),
      );
    } else {
      callback();
    }
  };

  // 创建
  createRule = (formData) => {
    const { type, onOk } = this.props;
    const { data } = this.state;

    const reqData = {
      users: data.users ? data.users.map((item) => item._userId) : [],
      operation_types: formData.operation_types || [],
      ips: formData.allowed_ip_list ? formData.allowed_ip_list.split(',') : [],
    };

    if (type === 'edit') {
      reqData.uuid = data.uuid;
    }

    console.log(reqData);

    exceed
      .fetch({
        api:
          type === 'edit'
            ? 'organization.grant_behavior.update'
            : 'organization.grant_behavior.new',
        params: { orgId },
        data: reqData,
      })
      .then((result) => {
        if (result) {
          Message.success({
            title: intl.get({
              id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.TheWhitelistRuleIsCreated',
              defaultMessage: '白名单规则新建成功',
            }),
          });

          this.setState({
            submitting: false,
          });

          this.onClose();
          onOk && onOk();
        } else {
          Message.error({
            title: intl.get({
              id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.UnableToCreateAWhitelist',
              defaultMessage: '白名单规则新建失败',
            }),
          });

          this.setState({
            submitting: false,
          });
        }
      })
      .fail(() => {
        this.setState({ submitting: false });
      });
  };

  onUserChange = (users) => {
    const { data } = this.props;
    this.field.setValue('users', users);
    this.setUserError(!users.length);
    this.setState({
      data: {
        ...data,
        users,
      },
    });
  };

  setUserError = (hasError) => {
    this.field.setError(
      'users',
      hasError ? (
        <div>
          <YunxiaoIcon type="delete-fill" />
          <span className="next-form-item-help-text">
            {intl.get({
              id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.ThisParameterIsRequired',
              defaultMessage: '该项为必填项',
            })}
          </span>{' '}
        </div>
      ) : (
        ''
      ),
    );
  };

  render() {
    const { field } = this;
    const { init } = this.field;
    const { data } = this.state;
    const { type } = this.props;
    const { users = [], operation_types = [], allowed_ip_list = '' } = data;

    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            className="overflow-auto-dialog"
            visible
            onClose={this.onClose}
            onCancel={this.onClose}
            okProps={{
              loading: this.state.submitting,
            }}
            onOk={this.onHandleSubmit}
            title={
              type === 'edit'
                ? intl.get({
                    id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.EditAWhitelistRule',
                    defaultMessage: '编辑白名单规则',
                  })
                : intl.get({
                    id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.CreateAWhitelistRule',
                    defaultMessage: '新建白名单规则',
                  })
            }
            style={{
              width: '600px',
            }}
          >
            <Form labelAlign="top" field={field} className="whitelist-rule-form">
              <FormItem
                label={intl.get({
                  id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.Operator',
                  defaultMessage: '操作人',
                })}
                required
                validateState={this.field.getState('users') === 'error' ? 'error' : 'success'}
                help={this.field.getState('users') === 'error' ? this.field.getError('users') : ''}
                {...formItemLayout}
              >
                <div
                  ref={(o) => {
                    this.userContainer = o;
                  }}
                >
                  <MemberTrigger
                    onChange={(value) => {
                      this.onUserChange(value);
                    }}
                    value={users}
                    container={() => this.userContainer}
                    multiple
                    isInviteUrl
                  />
                </div>
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.OperationType',
                  defaultMessage: '操作类型',
                })}
                required
                {...formItemLayout}
              >
                <Checkbox.Group
                  itemDirection="hoz"
                  {...init('operation_types', {
                    initValue: operation_types,
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },

                      {
                        validator: this.typeValidator,
                      },
                    ],

                    props: {
                      onChange: (v) => {
                        this.setState({
                          data: {
                            ...data,
                            operation_types: v,
                          },
                        });
                      },
                    },
                  })}
                >
                  {operationTypes.map((item) => {
                    return <Checkbox value={item.value}>{item.label}</Checkbox>;
                  })}
                </Checkbox.Group>
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.SourceIpAddress',
                  defaultMessage: '来源IP',
                })}
                required
                {...formItemLayout}
              >
                <Input.TextArea
                  {...init('allowed_ip_list', {
                    initValue: allowed_ip_list,
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },

                      {
                        validator: this.ipValidator,
                      },
                    ],

                    props: {
                      onChange: (v) => {
                        this.setState({
                          data: {
                            ...data,
                            allowed_ip_list: v,
                          },
                        });
                      },
                    },
                  })}
                  placeholder={intl.get({
                    id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.EnterTheSourceIpAddress',
                    defaultMessage: '请输入来源IP',
                  })}
                />
              </FormItem>
              <div className="rule-extra-info">
                <span>•</span>
                {intl.get({
                  id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.SeparateMultipleIpAddressesWith',
                  defaultMessage: '多个 IP 用英文逗号隔开，逗号前后不加空格。',
                })}
              </div>
              <div className="rule-extra-info">
                <span>•</span>
                {intl.get({
                  id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.YouCanSetCidrBlocks',
                  defaultMessage: '支持设置 IP 段，如 10.10.10.0/24。',
                })}
              </div>
              <div className="rule-extra-info">
                <span>•</span>
                {intl.get({
                  id: 'code-assets.sensitiveBehaviorMonitor.newRuleModal.IndicatesThatAllSourcesAre',
                  defaultMessage: '0.0.0.0/0 表示允许全部来源。',
                })}
              </div>
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
